package ngames.com.sushitv.net.okhttp.callback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import ngames.com.sushitv.core.ErrorEvent;
import okhttp3.Response;

/**
 * Created by Administrator on 2016/1/20.
 */
public class RequestCallBackDownload extends RequestCallBack<File> {
    /**
     * 目标文件存储的文件夹路径
     */
    private String mDestFileDir;
    /**
     * 目标文件存储的文件名
     */
    private String mDestFileName;

    public RequestCallBackDownload(String destFileDir, String destFileName) {
        mDestFileDir = destFileDir;
        mDestFileName = destFileName;
    }

    @Override
    public File parseResponse(Response response) {
        File file = saveFile(response);
        if (file != null && file.exists()) {
            success(file);
        } else {
            failure(ErrorEvent.CODE_ERROR_RESOLVE, null);
        }
        return file;
    }

    @Override
    public void onFailure(String code, String msg) {

    }

    @Override
    public void onSuccess(File response) {

    }

    private File saveFile(Response response) {
        InputStream is = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream fos = null;
        File file = null;
        try {
            is = response.body().byteStream();
            final long total = response.body().contentLength();
            long sum = 0;
            File dir = new File(mDestFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            file = new File(dir, mDestFileName);
            fos = new FileOutputStream(file);
            while ((len = is.read(buf)) != -1) {
                sum += len;
                fos.write(buf, 0, len);
                final long finalSum = sum;
                progress((int) (finalSum / total));
            }
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException e) {
            }
            try {
                if (fos != null) fos.close();
            } catch (IOException e) {
            }
        }
        return file;
    }
}
